package com.olddriver.crm.web.controller;

import com.olddriver.crm.annotation.PermissionName;
import com.olddriver.crm.domain.Permission;
import com.olddriver.crm.service.IPermissionService;
import com.olddriver.crm.util.JsonResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private ApplicationContext atx;

    @RequestMapping("list")
    @RequiresPermissions("permission:list")
    @PermissionName("查看权限")
    public String list() {
        return "permission/list";
    }

    @RequestMapping("listAll")
    @ResponseBody
    public List<Permission> listAll() {
        return permissionService.listAll();
    }

    @ResponseBody
    @RequestMapping("load")
    @RequiresPermissions("permission:load")
    @PermissionName("加载权限")
    public JsonResult load() {
        List<String> resourses = permissionService.getResourses();
        Map<String, Object> controllers = atx.getBeansWithAnnotation(Controller.class);
        try {

            for (Object contoller : controllers.values()) {
                /*使用shiro后controller对象都变为代理类,需要获取其父类中的方法*/
                Method[] methods = contoller.getClass().getSuperclass().getDeclaredMethods();
                for (Method method : methods) {
                    RequiresPermissions resource = method.getAnnotation(RequiresPermissions.class);
                    if (resource != null) {
                        if (!resourses.contains(resource.value()[0])) {
                            Permission permission = new Permission();
                            permission.setResourse(resource.value()[0]);
                            PermissionName name = method.getAnnotation(PermissionName.class);
                            if (name != null) {
                                permission.setName(name.value());
                            }
                            permissionService.insert(permission);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.faliure();
        }
        return JsonResult.success();
    }
}
